<script setup lang="ts">
import ok from '@/components/icons/ok.vue'
import info from '@/components/icons/info.vue'
import warning from '@/components/icons/warning.vue'
import error from '@/components/icons/error.vue'
import {ref} from 'vue'

interface MessageItem {
  id: number
  text: string
  type: 'success' | 'error' | 'info' | 'warning'
}

const messages = ref<MessageItem[]>([])

let seed = 0

// 外部调用的函数
function addMessage(text: string, type: MessageItem['type'], duration = 3000) {
  const id = seed++
  messages.value.push({id, text, type})

  setTimeout(() => {
    messages.value = messages.value.filter((msg) => msg.id !== id)
  }, duration)
}

// 暴露全局调用方法
defineExpose({addMessage})
</script>

<template>
  <teleport to="body">
    <div class="t-message-container">
      <transition-group name="slide-fade" tag="div">
        <div
            v-for="item in messages"
            :key="item.id"
            class="t-message"
            :class="`t-message--${item.type}`"
        >
          <ok v-if="item.type === 'success'" class="item-icon"></ok>
          <warning v-else-if="item.type === 'warning'" class="item-icon"></warning>
          <error v-else-if="item.type === 'error'" class="item-icon"></error>
          <info v-else class="item-icon"></info>
          <span>{{ item.text }}</span>
        </div>
      </transition-group>
    </div>
  </teleport>
</template>

<style scoped>
.t-message-container {
  position: fixed;
  top: 10px;
  left: 0;
  right: 0;
  z-index: 9999;
  pointer-events: none;
}

.t-message {
  min-width: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 10px auto;
  padding: 7px 20px;
  border-radius: 4px;
  background-color: rgba(255, 255, 255, 0.7);
  backdrop-filter: blur(8px);
  -webkit-backdrop-filter: blur(8px);
  color: #000;
  box-shadow: 0 4px 10px rgba(0, 0, 0, 0.15);
  font-size: 14px;

  width: fit-content;
  max-width: 80vw;
  word-break: break-word;
}

/*.t-message--success {
  background-color: #67c23a;
}

.t-message--error {
  background-color: #f56c6c;
}

.t-message--info {
  background-color: #909399;
}

.t-message--warning {
  background-color: #e6a23c;
}*/

/* 动画过渡效果 */
.slide-fade-enter-active,
.slide-fade-leave-active {
  transition: all 0.3s ease;
}

.slide-fade-enter-from,
.slide-fade-leave-to {
  opacity: 0;
  transform: translateY(-10px);
}

.item-icon {
  display: inline-block;
  vertical-align: middle;
  margin-right: 8px;
}
</style>
